package com.chinapost.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinapost.dao.BaseDaoI;
import com.chinapost.po.Tdqcd;
import com.chinapost.po.Tmonth;
import com.chinapost.service.DqcdServiceI;
import com.chinapost.util.MyUtil;
import com.chinapost.vo.DataGrid;
import com.chinapost.vo.Dqcd;

@Service("dqcdService")
public class DqcdServiceImpl implements DqcdServiceI {

	@Autowired
	private BaseDaoI<Tdqcd> dqcdDao;
	@Autowired
	private BaseDaoI<Tmonth> monthDao;

	@Override
	public int addDqcds(Dqcd dqcd) {
		Charset cs = Charset.forName("GBK");
		Path path = Paths.get(dqcd.getFilename());
		String hql = " delete from Tdqcd";
		dqcdDao.executeHql(hql);
		int i = 0;
		try {
			BufferedReader reader = Files.newBufferedReader(path, cs);
			// InputStreamReader read = new InputStreamReader(
			// new FileInputStream(file), "GBK");
			// BufferedReader reader = new BufferedReader(read);
			String line = null;
			while ((line = reader.readLine()) != null) {
				Tdqcd t = getDqcd(line);
				if (t != null) {
//					Tdqcd tdqcd = dqcdDao.get(Tdqcd.class, t.getCzh());
//					if (tdqcd == null) {
						dqcdDao.save(t);
						i++;
						System.out.println(i);
//					} else {
//						BeanUtils.copyProperties(t, tdqcd);
//					}
				}
			}
			reader.close();
			Tmonth tmonth = monthDao.get(Tmonth.class, 1);
			if (tmonth!=null){
				tmonth.setCmonth(dqcd.getCmonth());
			}else{
				Tmonth t1 = new Tmonth();
				t1.setCid(1);
				t1.setCmonth(dqcd.getCmonth());
				monthDao.save(t1);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		File f = new File(dqcd.getFilename());
		if (f.exists() && f.isFile()) {
			f.delete();
		}
		return i;
	}

	private Tdqcd getDqcd(String line) {
		// 跳过第一个字符不为3的无效行
		if (!StringUtils.isEmpty(line) && line.substring(0, 1).equals("3")) {
			// System.out.println(line);
			Tdqcd t = new Tdqcd();
			// 因为含有中文姓名，所以通过先转成byte[]字节码，然后再分割成相应的字段
			byte[] bytes = null;
			try {
				bytes = line.getBytes("GBK");
				// 处理某些行第49,50列多出空格的问题,如果是空格删除
				while (bytes[49] != 48) {
					bytes = MyUtil.delByte(bytes, 49);
				}
				// 存期为不固定和7天的记录忽略
				if (MyUtil.substr(bytes, 10, 8).trim().equals("不固定") || MyUtil.substr(bytes, 10, 8).trim().equals("7")) {
					return null;
				}
				// 状态为1，没有销户日期的记录直接返回null，忽略该行
				if (Integer.parseInt(MyUtil.substr(bytes, 89, 5).trim()) == 1 && (bytes.length == 94 || MyUtil.substr(bytes, 95, 8).trim().length() == 0)) {
					return null;
				}
				// System.out.println(bytes.length);
				t.setCkhj(MyUtil.substr(bytes, 0, 8));// 开户局
				t.setCcq(Integer.parseInt(MyUtil.substr(bytes, 10, 8).trim()));// 设置存期
				t.setCzh(MyUtil.substr(bytes, 19, 19).trim());// 设置账号
				t.setCxm(MyUtil.substr(bytes, 39, 8).trim());// 姓名
				t.setCkhr(MyUtil.substr(bytes, 48, 8));// 开户日
				t.setCye(Double.parseDouble(MyUtil.substr(bytes, 57, 13).trim()));// 账号余额
				t.setCqxr(MyUtil.substr(bytes, 71, 8));// 起息日
				t.setCdqr(MyUtil.substr(bytes, 80, 8));// 到期日
				t.setCzt(Integer.parseInt(MyUtil.substr(bytes, 89, 5).trim()));
				// 某些行没有销户日期，做个判断
				if (bytes.length > 96 && MyUtil.substr(bytes, 95, 8).trim().length() > 0) {
					t.setCxhr(MyUtil.substr(bytes, 95, 8));// 销户日
				}
				// 某些行没有销户金额，做个判断
				if (bytes.length > 96 && MyUtil.substr(bytes, 104, 13).trim().length() > 0) {
					t.setCxhje(Double.parseDouble(MyUtil.substr(bytes, 104, 13).trim()));// 销户金额
				}
				if (bytes.length > 119) {
					t.setCglzh(MyUtil.substr(bytes, 118, 19).trim());// 设置关联账号
				}
				return t;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public DataGrid datagrid(Dqcd dqcd) {
		DataGrid dg = new DataGrid();
		dg.setRows(listRows(find(dqcd)));
		dg.setTotal(total(dqcd));
		return dg;
	}

	private Long total(Dqcd dqcd) {
		String hql = "select count(*) from Tdqcd t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(dqcd, hql, params);
		return dqcdDao.count(hql, params);
	}

	private List<Tdqcd> find(Dqcd dqcd) {
		String hql = "from Tdqcd t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(dqcd, hql, params);
		if (dqcd.getOrder() != null && dqcd.getSort() != null) {
			hql += " order by " + dqcd.getSort() + " " + dqcd.getOrder();
		}
		return dqcdDao.find(hql, params, dqcd.getPage(), dqcd.getRows());
	}

	private List<Dqcd> listRows(List<Tdqcd> lt) {
		List<Dqcd> rows = new ArrayList<Dqcd>();
		if (lt != null && lt.size() > 0) {
			for (Tdqcd t : lt) {
				Dqcd sub = new Dqcd();
				BeanUtils.copyProperties(t, sub);
				rows.add(sub);
			}
		}
		return rows;
	}

	private String addWhere(Dqcd dqcd, String hql, Map<String, Object> params) {
		if (dqcd != null && dqcd.getCzh() != null && !dqcd.getCzh().trim().equals("")) {
			hql += " and t.czh like :zh ";
			params.put("zh", "%%" + dqcd.getCzh() + "%%");
		}
		return hql;
	}

	@Override
	public void edit(Dqcd dqcd) {
		Tdqcd t = dqcdDao.get(Tdqcd.class, dqcd.getCzh());
		BeanUtils.copyProperties(dqcd, t);
	}

	

}
